package com.sl.au.controller;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.sl.au.entity.Account;
import com.sl.au.entity.Attachment;
import com.sl.au.service.AttachmentService;
import com.sl.au.service.StorageFileNotFoundException;
import com.sl.utils.DataConverter;

@Controller
@RequestMapping(value = "/a")
public class AttachmentController extends BaseController {

	@Autowired
	private AttachmentService attachmentService;
	
	
	String filesRoot="c:/upload";	

	/**
	 * 附件下载，显示所有附件 用于实体中只有一类附件，返回所有附件
	 * 
	 * @param model
	 * @param parentId
	 *            附件所在实体ID
	 * @param groupId
	 *            附件名称，如：方案附件
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/{parentId}/{groupId}/{del}", method = RequestMethod.GET)
	public String listUploadedFiles(Model model, @PathVariable String del, @PathVariable String parentId,
			@PathVariable String groupId) {
		model.addAttribute("del", del);
		model.addAttribute("files", attachmentService.getByParentId(parentId, groupId));
		model.addAttribute("groupId", groupId);
		return "attachment/downloadlist";
	}

	/**
	 * @param filename
	 * @return 通过存储时的UUID文件名下载单个附件
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/files/{filename:.+}", method = RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<Resource> serveFile(@PathVariable String filename) throws UnsupportedEncodingException {

		Resource file = attachmentService.loadAsResource(filename);
		Attachment a = attachmentService.getRepository().findBySavedFileName(filename);
		/*
		 * if(null==a){ return ResponseEntity .notFound()
		 * .header(HttpHeaders.CONTENT_TYPE,"") .body(file); }
		 */
		String originalFileName = a.getOriginalFileName();
		return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION,
				"attachment; charset=UTF-8;filename=\"" + java.net.URLEncoder.encode(originalFileName, "UTF-8") + "\"")
				.body(file);
	}

	
	
	/**
	 * 附件上传处理 *
	 */
	@RequestMapping(value = "/{parentId}/{groupId}", method = RequestMethod.POST)
	public @ResponseBody String handleFileUploadMultiple(@RequestParam("file") MultipartFile file,
			HttpServletRequest request, @PathVariable String parentId, @PathVariable String groupId,
			RedirectAttributes redirectAttributes) {

		Account account = (Account) request.getSession().getAttribute("account");
		String sender = "";
		if (null != account)
			sender = account.getUser().getName();
		attachmentService.save(file, sender, parentId, groupId);
		redirectAttributes.addFlashAttribute("files", attachmentService.getByParentId(parentId, groupId));

		return "redirect:/a/" + parentId + "/" + groupId;
	}

	/**
	 * 附件上传处理 mobile *
	 */
	@RequestMapping(value = "/{parentId}/{groupId}/json", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> handleFileUploadMultipleMobile(@RequestParam("file") MultipartFile file,
			@PathVariable String parentId, @PathVariable String groupId) {

		Map<String, Object> map = new HashMap<>();
		String getlist=request.getParameter("getlist");
		map.put("code", -1);
		Account account = this.getMyAccount();
		String sender = "";
		if (null != account)
			sender = account.getUser().getName();
		attachmentService.save(file, sender, parentId, groupId);
		if(StringUtils.hasText(getlist) && getlist.equals("1")){
			List<Attachment> list=new ArrayList<>();
			list=attachmentService.getRepository().findByParentIdAndGroupId(parentId, groupId);
			map.put("data", list);
		}
		map.put("code", 0);
		return map;
	}

	/*
	 * 获得附件，mobile
	 */
	@RequestMapping(value = "/{parentId}/{groupId}/json", method = RequestMethod.GET)
	public @ResponseBody Map<String,Object> getAList(@PathVariable String parentId, @PathVariable String groupId) {
		List<Attachment> list = new ArrayList<>();
		Map<String, Object> map = new HashMap<>();
		list = attachmentService.getRepository().findByParentIdAndGroupId(parentId, groupId);
		map.put("data", list);
		map.put("code", 0);
		return map;
	}
	
	/*
	 * 获得parentid的附件，mobile
	 */
	@RequestMapping(value = "/{parentId}/json", method = RequestMethod.GET)
	public @ResponseBody Map<String,Object> getParentAList(@PathVariable String parentId) {
		List<Attachment> list = new ArrayList<>();
		Map<String, Object> map = new HashMap<>();
		list = attachmentService.getRepository().findByParentId(parentId);
		map.put("data", list);
		map.put("code", 0);
		return map;
	}
	
	@RequestMapping(value = "/files/delete/{id}", method = RequestMethod.POST)
	public @ResponseBody String deleteAFile(@PathVariable String id) {
		if (null != id) {
			attachmentService.deleteA(id);
		}
		return "ok";
	}

	/**
	 * 附件上传下载演示
	 * 
	 * @return
	 */
	@RequestMapping(value = "/demo", method = RequestMethod.GET)
	public ModelAndView demo() {

		ModelAndView mv = this.createLayoutView("attachment/demo");
		return mv;
	}

	@ExceptionHandler(StorageFileNotFoundException.class)
	public ResponseEntity handleStorageFileNotFound(StorageFileNotFoundException exc) {
		return ResponseEntity.notFound().build();
	}

	/*
	 * 获得附件的个数，根据parentId
	 */
	@RequestMapping(value = "/attachmentNum/{parentId}/{groupId}", method = RequestMethod.POST)
	public @ResponseBody long getANum(@PathVariable String parentId, @PathVariable String groupId) {
		long count = 0;
		if (null != parentId) {
			List<Attachment> a = attachmentService.getRepository().findByParentIdAndGroupId(parentId, groupId);
			count = a.size();
		}
		return count;
	}
	
	 //通过用户id得到其在文件上传文件夹中的头像文件，返回文件流,适用于小的图片文件
    @RequestMapping(value="/avatar/{id}",method=RequestMethod.GET,produces=MediaType.ALL_VALUE)
    @ResponseBody public byte[] getImage(@PathVariable String id,HttpServletRequest request, HttpServletResponse response)
    {	    	
    	byte[] b =null;
    	try {
	    	
	    	File file=attachmentService.getUniqueNameFile(filesRoot, id);
	    	if(null==file) return null;
	    	RandomAccessFile f = new RandomAccessFile(file,"r");
	    	if(f==null) return null;
	         b = new byte[(int)f.length()];	        
				f.readFully(b);
				f.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}    	 
            return b;
    } 
    @RequestMapping(value="/tempfiles/delete/{id}",method=RequestMethod.GET,produces=MediaType.ALL_VALUE)
    @ResponseBody public Map<String,Object> delete(@PathVariable String id)
    {	    	
    	Map<String,Object> map=new HashMap<>();
    	map.put("code", -1);
    	
    	File file=attachmentService.getUniqueNameFile(filesRoot, id);
    	if(null!=file){
    		if(true==file.delete())
    			map.put("code", 0);
    	}
    
    	return map;
    } 
   
	

}
